//
//  CategoryViewController.swift
//  StoryDemo
//
//  Created by mac on 2019/7/8.
//  Copyright © 2019年 zhkj. All rights reserved.
//

import UIKit

class CategoryViewController: UIViewController,UITableViewDataSource,UICollectionViewDataSource,UITableViewDelegate,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    
    var loadDataSuccess:Bool = false
    var cateList = [Category]()
    var rightList = [Category]()
    @IBOutlet weak var search_view: UIView!
    var left_view:UITableView!
    var right_view:UICollectionView!
    var selectIndex:IndexPath = IndexPath(row: 0, section: 0)
    override func viewDidLoad() {
        super.viewDidLoad()
        search_view.layer.cornerRadius=5
        initLeftTable()
        initRightCollec()
        loaddata()
        // Do any additional setup after loading the view.
    }
    
    func initLeftTable(){
        left_view=UITableView(frame: CGRect(x: 0, y: 70, width: screenW/3, height: screenH-70),style:.plain)
        
        left_view.rowHeight = UITableView.automaticDimension
        left_view.estimatedRowHeight = 40
        left_view.dataSource=self
        left_view.delegate=self
        left_view.backgroundColor="#EEEEEE".color()
        left_view.separatorStyle=UITableViewCell.SeparatorStyle.none
        left_view.separatorInset=UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        left_view.contentInset=UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        left_view.register(UINib (nibName: "LeftTableViewCell", bundle: nil), forCellReuseIdentifier: "re")
        
        self.view.addSubview(left_view)
    }
    func initRightCollec(){
        let layout = UICollectionViewFlowLayout()
        right_view=UICollectionView(frame: CGRect(x: screenW/3, y: 70, width: screenW/3*2, height: screenH-70),collectionViewLayout: layout)
        right_view.dataSource=self
        right_view.delegate=self
        right_view.backgroundColor=UIColor.white
        right_view.contentInset=UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        right_view.register(UINib (nibName: "CategoryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "right")
        right_view.register(UINib (nibName: "HeadCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "head")
        
        self.view.addSubview(right_view)
    }
    func loaddata(){
        var d = ["app_key":app_key,
                 "timestamp":getTimestamp()
            ] as [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.get(url: GetCategories, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            ss.loadDataSuccess = true
            let cateRes=CategoryResult.init(json: res)
            ss.cateList=cateRes.Categorys
            ss.left_view.reloadData()
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
            ss.loadDataSuccess = false
        }
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let padding: CGFloat =  20
        let collectionViewSize = collectionView.frame.size.width - 4*padding
        
        return CGSize(width: collectionViewSize/3, height: 100)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return rightList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return rightList[section].SubCategories.count
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        var reusableview:HeadCollectionReusableView!
        
        //分区头
        if kind == UICollectionView.elementKindSectionHeader{
            reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind,
                                                                           withReuseIdentifier: "head", for: indexPath)as!HeadCollectionReusableView
            //设置头部标题
            reusableview.title.text=rightList[indexPath.section].Name
        }
        //分区尾
        //        else if kind == UICollectionElementKindSectionFooter{
        //            reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind,
        //                                                                           withReuseIdentifier: "FooterView", for: indexPath)
        //
        //        }
        return reusableview
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.size.width, height: 40)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell=right_view.dequeueReusableCell(withReuseIdentifier: "right", for: indexPath) as!CategoryCollectionViewCell
        let cate=rightList[indexPath.section].SubCategories[indexPath.row]
        if let url = URL.init(string: cate.Image!){
            cell.icon.setImage(path: url)
        }
        cell.name.text=cate.Name
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let resultsViewController = ResultsViewController(keywords: "", cid: String(rightList[indexPath.section].SubCategories[indexPath.row].Id))
        self.navigationController?.pushViewController(resultsViewController, animated: false)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cateList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell=left_view.dequeueReusableCell(withIdentifier: "re", for: indexPath) as!
        LeftTableViewCell
        cell.name.text=cateList[indexPath.row].Name
        if selectIndex==indexPath {
            rightList=cateList[indexPath.row].SubCategories
            right_view.reloadData()
            if rightList.count>0 {
                let ind:IndexPath=IndexPath(row: 0, section: 0)
                right_view.scrollToItem(at: ind, at: UICollectionView.ScrollPosition.bottom, animated: false)
            }
            cell.name.textColor=UIColor.red
            cell.left_line.isHidden=false
            cell.right_line.isHidden=true
        }else{
            cell.name.textColor=UIColor.black
            cell.left_line.isHidden=true
            cell.right_line.isHidden=false 
        }
        cell.selectionStyle = .none
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectIndex=indexPath
        left_view.reloadData()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
